<?php
namespace App\Admin\Extensions\Show;

use Encore\Admin\Show\AbstractField;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;

class MultipleFile extends AbstractField
{
    public $escape = false;

    public $border = false;

    public function render($server = '', $download = true)
    {
        $value = $this->value;
        if ($value instanceof Arrayable) {
            $value = $value->toArray();
        }
        $lis = collect((array) $value)->filter()->map(function ($path) use ($server, $download) {
            $name = basename($path);

            $size = $url = '';

            if (url()->isValidUrl($path)) {
                $url = $path;
            } elseif ($server) {
                $url = $server.$path;
            } else {
                $storage = Storage::disk(config('admin.upload.disk'));
                if ($storage->exists($path)) {
                    $url = $storage->url($path);
                    $size = ($storage->size($path) / 1000).'KB';
                }
            }
            if (!$url) {
                return '';
            }

            $download = $download ? "download='$name'" : '';

            $html = <<<HTML
            <li style="margin-bottom: 0;">
                <span class="mailbox-attachment-icon"><i class="fa {$this->getFileIcon($name)}"></i></span>
                <div class="mailbox-attachment-info">
                    <div class="mailbox-attachment-name">
                        <i class="fa fa-paperclip"></i> {$name}
                    </div>
                    <span class="mailbox-attachment-size">
                        {$size}&nbsp;
                        <a href="{$url}" class="btn btn-default btn-xs pull-right" target="_blank" $download><i class="fa fa-cloud-download"></i></a>
                    </span>
                </div>
            </li>
HTML;
            return $html;
        })->implode('&nbsp;');
        return '<ul class="mailbox-attachments clearfix">'.$lis.'</ul>';
    }

    /**
     * @var array
     */
    protected $fileTypes = [
        'image'      => 'png|jpg|jpeg|tmp|gif',
        'word'       => 'doc|docx',
        'excel'      => 'xls|xlsx|csv',
        'powerpoint' => 'ppt|pptx',
        'pdf'        => 'pdf',
        'code'       => 'php|js|java|python|ruby|go|c|cpp|sql|m|h|json|html|aspx',
        'archive'    => 'zip|tar\.gz|rar|rpm',
        'txt'        => 'txt|pac|log|md',
        'audio'      => 'mp3|wav|flac|3pg|aa|aac|ape|au|m4a|mpc|ogg',
        'video'      => 'mkv|rmvb|flv|mp4|avi|wmv|rm|asf|mpeg',
    ];

    public function getFileIcon($file = '')
    {
        $extension = File::extension($file);

        foreach ($this->fileTypes as $type => $regex) {
            if (preg_match("/^($regex)$/i", $extension) !== 0) {
                return "fa-file-{$type}-o";
            }
        }

        return 'fa-file-o';
    }
}
